package aa

import (
	"fmt"
	"syscall"
)

var consoleHWND uintptr // 控制台窗口句柄（包内可见）

func A予控制台() {
	GetConsoleWindowHandle()
	HideConsoleWindow()
}

// 获取控制台窗口句柄
func GetConsoleWindowHandle() uintptr {
	kernel32, err := syscall.LoadLibrary("kernel32.dll")
	if err != nil {
		fmt.Printf("❌ 加载 kernel32.dll 失败: %v\n", err)
		return 0
	}
	defer syscall.FreeLibrary(kernel32)

	getConsoleWindowProc, err := syscall.GetProcAddress(kernel32, "GetConsoleWindow")
	if err != nil {
		fmt.Printf("❌ 获取 GetConsoleWindow 地址失败: %v\n", err)
		return 0
	}

	hwnd, _, errno := syscall.SyscallN(getConsoleWindowProc)
	if errno != 0 {
		fmt.Printf("❌ 获取控制台句柄失败: %v\n", errno)
		return 0
	}
	consoleHWND = hwnd
	return hwnd
}

// 隐藏控制台窗口
func HideConsoleWindow() {
	if consoleHWND == 0 {
		consoleHWND = GetConsoleWindowHandle()
	}
	user32, err := syscall.LoadLibrary("user32.dll")
	if err != nil {
		fmt.Printf("❌ 加载 user32.dll 失败: %v\n", err)
		return
	}
	defer syscall.FreeLibrary(user32)

	showWindowProc, err := syscall.GetProcAddress(user32, "ShowWindow")
	if err != nil {
		fmt.Printf("❌ 获取 ShowWindow 地址失败: %v\n", err)
		return
	}

	// SW_HIDE = 0
	_, _, errno := syscall.SyscallN(showWindowProc, consoleHWND, 0)
	if errno != 0 {
		fmt.Printf("❌ 隐藏控制台失败: %v\n", errno)
	}
}

// 显示控制台窗口
func ShowConsoleWindow() {
	if consoleHWND == 0 {
		consoleHWND = GetConsoleWindowHandle()
	}
	user32, err := syscall.LoadLibrary("user32.dll")
	if err != nil {
		fmt.Printf("❌ 加载 user32.dll 失败: %v\n", err)
		return
	}
	defer syscall.FreeLibrary(user32)

	showWindowProc, err := syscall.GetProcAddress(user32, "ShowWindow")
	if err != nil {
		fmt.Printf("❌ 获取 ShowWindow 地址失败: %v\n", err)
		return
	}

	// SW_SHOWNORMAL = 1
	_, _, errno := syscall.SyscallN(showWindowProc, consoleHWND, 1)
	if errno != 0 {
		fmt.Printf("❌ 显示控制台失败: %v\n", errno)
	}
}
